package start.spring.basic.util.common;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * ****************************************************************************
 * http请求ip工具类
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2023年2月17日
 ******************************************************************************
 */
public class RequestIpUtil {

	private static final String UNKONWN = "unknown";

	/**
	 * 获取请求ip
	 *	
	 * @param request
	 * @return
	 * @since           1.0
	 */
	public static String getRealip(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || UNKONWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKONWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKONWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip == null) {
			ip = "";
		}
			
		// 多次反向代理后会有多个ip值，第一个ip才是真实ip
		int index1 = ip.indexOf(",");
		if (index1 != -1) {
			ip = ip.substring(0, index1);
		}
		return ip;
	}
	
	/**
	 * 获取请求类型
	 *	
	 * @param request 请求
	 * @return 
	 * @since           1.0
	 */
	public static int getRequestType(HttpServletRequest request) {
		//未知类型
		int type = 0;
		if(request!=null) {
			String xRequestWith = request.getHeader("");
			//普通请求
			if(StringUtil.isEmpty(xRequestWith)) {
				type = 1;
				
			//ajax请求	
			}else {
				type = 2;
			}
		}
		return type;
	}
}
